/**
 * @Copyright: Interactive Business Solution Pte Ltd, Singapore
 * @Author: Li Wen, 2008-01-18
 * @Version: 071224.001
 * Data access object of Pin model
 */
package com.ibsol.database
{
	import com.ibsol.model.Pin;
	
	import flash.data.SQLConnection;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	public class PinDAO
	{
		private var _tourixDBConn:SQLConnection;
		
		public function PinDAO()
		{
			_tourixDBConn = DBConnManager.getConnection("tourix");
		}
		
		public function loadPackagePin(packageid:int, resultHandler:Function, faultHandler:Function = null):void
		{
			var sqlStr:SQLStatement = new SQLStatement();
			sqlStr.sqlConnection = _tourixDBConn;
			sqlStr.text = "SELECT t.id as tourItemid, t.packageid, t.name, t.desp, c.name as city, c.country, c.x, c.y " + 
					"FROM touritem as t, city as c where packageid = " + packageid +" and t.cityid = c.id";
			sqlStr.addEventListener(SQLEvent.RESULT,
				function (event:SQLEvent):void
				{
					resultHandler.call(this, typeArray(sqlStr.getResult().data));
				});
			sqlStr.addEventListener(SQLErrorEvent.ERROR, faultHandler == null ? sqlErrorHandler : faultHandler);
			sqlStr.execute();
		}
		/**
		 * Converts database object to Pin class
		 * @param:	o:Object	database return object
		 * @return:	Pin			Pin object after conversion
		 */
		private function typeObject(o:Object):Pin
		{
			var p:Pin = new Pin();
			p.packageid = o.packageid;
			p.name = o.name;
			p.desp = o.desp;
			p.city = o.city;
			p.country = o.country;
			p.x = o.x;
			p.y = o.y
			p.tourItemid = o.tourItemid;
			return p;
		}
		/**
		 * Converts array object to Marker array collection
		 * @param: a:Array array of objects returned by SQL
		 * @return: ArrayCollection of Marker after conversion from Array
		 */
		private function typeArray(a:Array):ArrayCollection
		{
			if (a==null) return null;
			var ac:ArrayCollection = new ArrayCollection();
			for (var i:int; i<a.length; i++)
			{
				ac.addItem(typeObject(a[i]));
			}
			return ac;
		}
		/**
		 * Default SQL error handler, if above functions' fault handlers are null, this error handler is applied
		 * @param: event:SQLError	SQL Error event will be handled if there is an error
		 * @return: void
		 */
		private function sqlErrorHandler(event:SQLErrorEvent):void
		{
			mx.controls.Alert.show(event.text, "Error");
			trace(event.text);
		}
	}
}